<template>
  <div class="gspRov">
    <h2>Login to your account</h2>
    <form @submit.prevent="handleSubmit">
      <ul v-if="errors" class="errors">
        <li v-for="(error, index) in errors" :key="index">
          {{ `${error.field} ${error.message}` }}
        </li>
      </ul>
      <input v-if="!isLogin" v-model="user.username" type="username" placeholder="username" />
      <input v-model="user.email" type="email" placeholder="email" />
      <input v-model="user.password" type="password" placeholder="password" />
      <div class="action input-group">
        <span class="pointer" @click="onSignupClick">Signup instead</span>
        <button :disabled="isLoading">Login</button>
      </div>
    </form>
  </div>
</template>

<script lang="ts">
import { login, register } from '@/api/user'
import { defineComponent, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from '@/store'

const useLogin = () => {
  const router = useRouter()
  const store = useStore()
  const route = useRoute()
  console.log(router)
  const user = reactive({
    username: '',
    email: '',
    password: ''
  })
  const isLogin = ref(false)
  const errors = ref([])
  const isLoading = ref(false)

  isLogin.value = !!router.currentRoute.value.query.isLogin

  const handleSubmit = async () => {
    isLoading.value = true
    errors.value = []
    try {
      const { data } = await (isLogin.value ? login(user) : register(user))
      store.commit('setUser', data.user)
      const redirect = (route.query.redirect || '/') as string
      router.push(redirect)
    } catch (err) {
      if (err.response.status === 422) {
        errors.value = err.response.data.detail
      }
    }
    isLoading.value = false
  }

  return {
    user,
    handleSubmit,
    errors,
    isLoading,
    isLogin
  }
}

export default defineComponent({
  name: 'LoginIndex',
  setup () {
    const router = useRouter()
    const onSignupClick = () => {
      router.push({
        path: '/register'
      })
    }
    return {
      onSignupClick,
      ...useLogin()
    }
  }
})
</script>
